package ua.kpi.ipsa.expert.api.db;

import com.sleepycat.bind.tuple.IntegerBinding;
import com.sleepycat.bind.tuple.TupleInput;
import com.sleepycat.bind.tuple.TupleOutput;
import com.sleepycat.je.DatabaseEntry;
import com.sleepycat.je.SecondaryDatabase;
import com.sleepycat.je.SecondaryKeyCreator;

public class PlagiarismHypoTuple {

	public static final int USER_AGREEZ = 1;
	public static final int USER_DISAGREEZ = 2;
	public static final int NO_INFO = 3;

	public int plagiarismHypoPK;

	public double veracity;
	public int algorithmFK;

	// code1 - the code to which this hypo is related
	public int code1FK;
	// code2 - additional code reference
	public int code2FK;

	public int code1PlagStart;
	public int code1PlagEnd;
	public int code2PlagStart;
	public int code2PlagEnd;

	public int userOpinion;

	public PlagiarismHypoTuple() {
	}

	public PlagiarismHypoTuple(int plagiarismHypoTuplePK) {
		this.plagiarismHypoPK = plagiarismHypoTuplePK;
	}

	PlagiarismHypoTuple(DatabaseEntry key, DatabaseEntry data) {
		setKeyEntry(key);
		setValueEntry(data);
	}

	DatabaseEntry getKeyEntry() {
		DatabaseEntry entry = new DatabaseEntry();
		IntegerBinding.intToEntry(plagiarismHypoPK, entry);
		return entry;
	}

	void setKeyEntry(DatabaseEntry entry) {
		plagiarismHypoPK = IntegerBinding.entryToInt(entry);
	}

	DatabaseEntry getValueEntry() {
		DatabaseEntry entry = new DatabaseEntry();
		TupleOutput out = new TupleOutput();
		out.writeDouble(veracity);
		out.writeInt(algorithmFK);
		out.writeInt(code1FK);
		out.writeInt(code2FK);
		out.writeInt(code1PlagStart);
		out.writeInt(code1PlagEnd);
		out.writeInt(code2PlagStart);
		out.writeInt(code2PlagEnd);
		out.writeInt(userOpinion);
		entry.setData(out.getBufferBytes(), out.getBufferOffset(),
				out.getBufferLength());
		return entry;
	}

	void setValueEntry(DatabaseEntry entry) {
		TupleInput in = new TupleInput(entry.getData(), entry.getOffset(),
				entry.getSize());
		veracity = in.readDouble();
		algorithmFK = in.readInt();
		code1FK = in.readInt();
		code2FK = in.readInt();
		code1PlagStart = in.readInt();
		code1PlagEnd = in.readInt();
		code2PlagStart = in.readInt();
		code2PlagEnd = in.readInt();
		userOpinion = in.readInt();
	}

	static final SecondaryKeyCreator CODE1_CREATOR = new SecondaryKeyCreator() {

		@Override
		public boolean createSecondaryKey(SecondaryDatabase secondary,
				DatabaseEntry key, DatabaseEntry data, DatabaseEntry result) {
			IntegerBinding.intToEntry(
					new PlagiarismHypoTuple(key, data).code1FK, result);
			return true;
		}
	};
}